package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.CustomerInfoSource;
import com.isunland.managesystem.entity.CustomerType;
import com.isunland.managesystem.entity.CustomerUnit;
import com.isunland.managesystem.entity.CustomerUnitOriginal;
import com.isunland.managesystem.entity.CustomerUnitStatu;
import com.isunland.managesystem.entity.HolyType;
import com.isunland.managesystem.entity.Product;
import com.isunland.managesystem.entity.ProductOriginal;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

public class CustomerDialogFragment extends DialogFragment {
  protected static final String TAG = "CustomerUnitDialogFragment";
  public static final String EXTRA_TYPE = "com.isunland.managesystem.ui.extra_type";
  public static final int VALUE_TYPE_CUSTOMER_UNIT = 0;
  public static final int VALUE_TYPE_CUSTOMER_PRODUCT = 1;
  protected static final String EXTRA_VALUE = "com.isunland.managesystem.ui.extra_value";
  protected static final int VALUE_TYPE_CUSTOMER_UNIT_STATE = 2;
  protected static final int VALUE_TYPE_CUSTOMER_TYPE = 3;
  protected static final int VALUE_TYPE_CUSTOMER_INFO_SOURCE = 4;
  protected static final int VALUE_TYPE_HOLY_TYPE = 5;
  protected static final int VALUE_TYPE_CUSTOMER_RESOURCE = 9;
  /**
   * 附件
   */
  public static final int VALUE_TYPE_CUSTOMER_INFO_EXTRA = 6;
  /**
   * 客户
   */
  public static final int VALUE_TYPE_CUSTOMER_NAME = 7;
  /**
   * 需求
   */
  public static final int VALUE_TYPE_CUSTOMER_NEED = 8;
  private BaseVolleyActivity mActivity;

  private ArrayAdapter<CustomerDialog> mAdapter;

  private AlertDialog mDialog;
  private int mType;

  @Override public Dialog onCreateDialog(Bundle savedInstanceState) {

    Builder builderSingle = new AlertDialog.Builder(getActivity());
    View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_progress, null);
    builderSingle.setView(v);
    mDialog = builderSingle.create();

    return mDialog;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    mType = getArguments().getInt(EXTRA_TYPE);
    mActivity = (BaseVolleyActivity) getActivity();
    volleyPostCustomerUnitList();
    super.onCreate(savedInstanceState);
  }

  private void volleyPostCustomerUnitList() {
    if (!MyUtils.isNetLink(getActivity())) {
      Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_SHORT).show();
      return;
    }
    String url = "";
    HashMap<String, String> params = new HashMap<String, String>();

    switch (mType) {
      case VALUE_TYPE_CUSTOMER_UNIT:
        url = ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_UNIT_LIST);
        params.put("dataStatus", "publish");
        params.put("select", "true");
        params.put("orderField", "district_code");
        params.put("orderSeq ", "asc");
        break;
      case VALUE_TYPE_CUSTOMER_PRODUCT:
        url = ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_PRODUCT_LIST);
        params.put("memberCode", CurrentUser.newInstance(getActivity()).getJobNumber());
        params.put("dataStatus", "publish");
        break;
      case VALUE_TYPE_CUSTOMER_UNIT_STATE:
        url = ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_UNIT_STATE);

        params.put("dictFlg", "customerStatus");
        LogUtil.i("客户状态params===" + params);
        break;
      case VALUE_TYPE_CUSTOMER_RESOURCE:
        //客户来源
        url = ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_UNIT_STATE);
        params.put("dictFlg", "customerInfoFrom");
        break;
      case VALUE_TYPE_CUSTOMER_INFO_SOURCE:
        url = ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_UNIT_STATE);

        params.put("dictFlg", "customerInfoFrom");
        break;
      case VALUE_TYPE_CUSTOMER_TYPE:
        url = ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_UNIT_STATE);
        params.put("dictFlg", "customerContactMode");
        break;
      case VALUE_TYPE_HOLY_TYPE:
        url = ApiConst.getAbsoluteUrl(ApiConst.URL_HOLY_TYPE);
        params.put("dictFlag", "hrVacationType");
        break;
      default:
        break;
    }
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        LogUtil.i(TAG, "response=" + arg0);
        switch (mType) {
          case VALUE_TYPE_CUSTOMER_UNIT:
            resolveResponseCustomerUnit(arg0);

            break;
          case VALUE_TYPE_CUSTOMER_PRODUCT:
            resolveResponseCustomerProduct(arg0);

            break;

          case VALUE_TYPE_CUSTOMER_UNIT_STATE:
            resolveResponseCustomerUnitState(arg0);

            break;
          case VALUE_TYPE_CUSTOMER_RESOURCE:
            resolveResponseCustomerUnitState(arg0);

            break;
          case VALUE_TYPE_CUSTOMER_INFO_SOURCE:
            resolveResponseCustomerInfoSource(arg0);

            break;
          case VALUE_TYPE_CUSTOMER_TYPE:
            resolveResponseCustomerType(arg0);

            break;
          case VALUE_TYPE_HOLY_TYPE:
            resolveResponseHolyType(arg0);

            break;

          default:
            break;
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  private void resolveResponseCustomerUnit(String arg0) {

    try {
      CustomerUnitOriginal customerUnitOriginal =
          new Gson().fromJson(arg0, CustomerUnitOriginal.class);
      if (customerUnitOriginal == null || customerUnitOriginal.getRows() == null) {

        return;
      }

      List<CustomerUnit> customerUnit = customerUnitOriginal.getRows();
      ArrayList<CustomerDialog> customerDialogs = new ArrayList<CustomerDialog>();
      for (int i = 0; i < customerUnit.size(); i++) {
        customerDialogs.add(
            new CustomerDialog(customerUnit.get(i).getCustomerName(), customerUnit.get(i).getId()));
      }

      setAdapter(customerDialogs);
    } catch (Exception e) {
      LogUtil.e(TAG, "Exception", e);
    }
  }

  private void resolveResponseCustomerProduct(String arg0) {

    try {
      ProductOriginal productOriginal = new Gson().fromJson(arg0, ProductOriginal.class);
      if (productOriginal == null || productOriginal.getRows() == null) {

        return;
      }

      List<Product> product = productOriginal.getRows();
      ArrayList<CustomerDialog> customerDialogs = new ArrayList<CustomerDialog>();
      for (int i = 0; i < product.size(); i++) {
        customerDialogs.add(new CustomerDialog(product.get(i).getProductName(), ""));
      }

      setAdapter(customerDialogs);
    } catch (Exception e) {
      LogUtil.e(TAG, "Exception", e);
    }
  }

  private void resolveResponseCustomerUnitState(String arg0) {

    try {
      CustomerUnitStatu[] custoomerUnitStatus =
          new Gson().fromJson(arg0, CustomerUnitStatu[].class);
      if (custoomerUnitStatus == null || custoomerUnitStatus.length <= 0) {

        return;
      }

      ArrayList<CustomerDialog> customerDialogs = new ArrayList<CustomerDialog>();
      for (int i = 0; i < custoomerUnitStatus.length; i++) {
        customerDialogs.add(new CustomerDialog(custoomerUnitStatus[i].getName(),
            custoomerUnitStatus[i].getCustomAttrs()));
      }

      setAdapter(customerDialogs);
    } catch (Exception e) {
      LogUtil.e(TAG, "Exception", e);
    }
  }

  private void resolveResponseCustomerInfoSource(String arg0) {
    LogUtil.i("客户状态arg0===" + arg0);

    try {
      CustomerInfoSource[] custoomerInfoSource =
          new Gson().fromJson(arg0, CustomerInfoSource[].class);
      if (custoomerInfoSource == null || custoomerInfoSource.length <= 0) {

        return;
      }

      ArrayList<CustomerDialog> customerDialogs = new ArrayList<CustomerDialog>();
      for (int i = 0; i < custoomerInfoSource.length; i++) {
        customerDialogs.add(new CustomerDialog(custoomerInfoSource[i].getName(),
            custoomerInfoSource[i].getCustomAttrs()));
      }

      setAdapter(customerDialogs);
    } catch (Exception e) {
      LogUtil.e(TAG, "Exception", e);
    }
  }

  private void resolveResponseCustomerType(String arg0) {

    try {
      CustomerType[] customerType = new Gson().fromJson(arg0, CustomerType[].class);
      if (customerType == null || customerType.length <= 0) {

        return;
      }

      ArrayList<CustomerDialog> customerDialogs = new ArrayList<CustomerDialog>();
      for (int i = 0; i < customerType.length; i++) {
        customerDialogs.add(
            new CustomerDialog(customerType[i].getName(), customerType[i].getCustomAttrs()));
      }

      setAdapter(customerDialogs);
    } catch (Exception e) {
      LogUtil.e(TAG, "Exception", e);
    }
  }

  private void resolveResponseHolyType(String arg0) {

    try {
      HolyType[] holyTypes = new Gson().fromJson(arg0, HolyType[].class);
      if (holyTypes == null || holyTypes.length <= 0) {

        return;
      }

      ArrayList<CustomerDialog> customerDialogs = new ArrayList<CustomerDialog>();
      for (int i = 0; i < holyTypes.length; i++) {
        customerDialogs.add(new CustomerDialog(holyTypes[i].getTEXT(), holyTypes[i].getID()));
      }

      setAdapter(customerDialogs);
    } catch (Exception e) {
      LogUtil.e(TAG, "Exception", e);
    }
  }

  private void setAdapter(ArrayList<CustomerDialog> customerDialogs) {
    mDialog.dismiss();

    if (mAdapter == null) {
      mAdapter = new ArrayAdapter<CustomerDialog>(getActivity(),
          android.R.layout.select_dialog_singlechoice, customerDialogs) {

        @Override public View getView(int position, View convertView, ViewGroup parent) {
          CustomerDialog user = getItem(position);
          if (convertView == null) {
            convertView = LayoutInflater.from(getContext())
                .inflate(android.R.layout.simple_list_item_1, parent, false);
          }
          TextView tvName = (TextView) convertView.findViewById(android.R.id.text1);

          tvName.setText(user.getName());

          return convertView;
        }
      };
    } else {
      mAdapter.clear();
      mAdapter.addAll(customerDialogs);
    }

    Builder builderSingle = new AlertDialog.Builder(getActivity());
    builderSingle.setAdapter(mAdapter, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        CustomerDialog customerDialog = mAdapter.getItem(which);

        if (getTargetFragment() == null) return;
        Intent i = new Intent();
        i.putExtra(EXTRA_VALUE, customerDialog);

        getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
      }
    });
    builderSingle.create().show();
  }

  public static CustomerDialogFragment newInstance(int type) {
    Bundle argsBundle = new Bundle();
    argsBundle.putInt(EXTRA_TYPE, type);
    CustomerDialogFragment fragment = new CustomerDialogFragment();
    fragment.setArguments(argsBundle);
    return fragment;
  }
}
